
<template>
  <router-view id="root" @login="loginDirect" @logout="logoutDirect"></router-view>
</template>

<script>
const testdata = {
  data: {
    name: "管理端",
    resources: [
      {
        id: "101001",
        name: "登录",
        url: "/login",
        method: "POST"
      },
      {
        id: "102001",
        name: "用户统计-查询",
        url: "/userstatic/*/*/*",
        method: "GET"
      }
    ],
    id: "2c9180895e172348015e1740805d000d",
    menus: [
      {
        id: "200100",
        name: "概览",
        parent_id: null,
        route: "overview",
      },
      {
        id: "200200",
        name: "版本管理",
        parent_id: null,
        route: "version",
      },
      {
        id: "200200",
        name: "版本详情",
        parent_id: null,
        route: "details",
      },
      {
        id: "200200",
        name: "需求管理",
        parent_id: null,
        route: "demand",
      },
      {
        id: "200200",
        name: "系统管理",
        parent_id: null,
        route: "system",
      },
      {
        id: "200200",
        name: "版本记录",
        parent_id: null,
        route: "record",
      },
      {
        id: "200200",
        name: "系统管理",
        parent_id: null,
        route: "demandlist",
      },
      {
        id: "200200",
        name: "版本记录",
        parent_id: null,
        route: "demanddetails",
      },
      {
        id: "200200",
        name: "系统管理",
        parent_id: null,
        route: "system",
      },
      {
        id: "200200",
        name: "部门管理",
        parent_id: null,
        route: "department",
      }
    ]
  },
  status: 200,
  statusText: "OK"
};

import Vue from "vue";
import axios from "../api";
import fullroutes from "../router/fullroutes";
import * as util from "../util";

//请求拦截句柄
let myInterceptor;

export default {
  data() {
    return {
      menuData: null,
      userData: null
    };
  },
  methods: {
    getPermission: function(userInfo) {
      let resourcePermission = {};
      if (Array.isArray(userInfo.resources)) {
        userInfo.resources.forEach(function(e, i) {
          let key = e.method.toLowerCase() + "," + e.url;
          resourcePermission[key] = true;
        });
      }
      return resourcePermission;
    },
    setInterceptor: function(resourcePermission) {
      let vm = this;
      myInterceptor = axios.interceptors.request.use(function(config) {
        console.warn(config);
        // 关闭权限限制
        // if (!resourcePermission[config.headers.permission]) {
        //   //调试信息
        //   alert("无访问权限，请联系系统管理员");
        //   //拦截请求
        //   return Promise.reject({
        //     message: "no permission"
        //   });
        // } else {
        //   delete config.headers.permission;
        // }
        return config;
      });
    },
    getRoutes: function(userInfo) {
      if (!userInfo.menus) {
        return console.warn(userInfo);
      }
      let vm = this;
      let allowedRouter = [];
      // 将菜单数据转成多维数组格式
      let arrayMenus = util.buildMenu(userInfo.menus);
      // 将多维数组转成对象格式
      let hashMenus = {};
      let setMenu2Hash = function(array, base) {
        array.map(key => {
          if (key.route) {
            let hashKey = ((base ? base + "/" : "") + key.route).replace(
              /^\//,
              ""
            );
            hashMenus["/" + hashKey] = true;
            if (Array.isArray(key.children)) {
              setMenu2Hash(key.children, key.route);
            }
          }
        });
      };
      setMenu2Hash(arrayMenus);
      console.warn(hashMenus);
      // 全局挂载hashMenus，用于实现路由守卫
      this.$root.hashMenus = hashMenus;
      // 筛选本地路由方法
      let findLocalRoute = function(array, base) {
        let replyResult = [];
        array.forEach(function(route) {
          let pathKey = (base ? base + "/" : "") + route.path;
          if (hashMenus[pathKey]) {
            if (Array.isArray(route.children)) {
              route.children = findLocalRoute(route.children, route.path);
            }
            replyResult.push(route);
          }
        });
        if (base) {
          return replyResult;
        } else {
          allowedRouter = allowedRouter.concat(replyResult);
        }
      };
      let originPath = util.deepcopy(fullroutes[0].children);
      findLocalRoute(originPath);
      return allowedRouter;
    },
    extendRoutes: function(allowedRouter) {
      let vm = this;
      let actualRouter = util.deepcopy(allowedRouter);
      actualRouter.map(e => {
        //复制子菜单信息到meta用于实现导航相关效果，非必需
        if (e.children) {
          if (!e.meta) e.meta = {};
          else e.meta.children = e.children;
        }
        //为动态路由添加守卫
        // return (e.beforeEnter = function(to, from, next) {
        //   if (vm.$root.hashMenus[to.path]) {
        //     next();
        //   } else {
        //     next("/401");
        //   }
        // });
      });
      let originPath = util.deepcopy(fullroutes);
      originPath[0].children = actualRouter;
      // 注入路由
      let rootRoute = [
        {
          path: "/",
          name: "首页",
          component: resolve => require([`../pages/App/App.vue`], resolve),
          children: actualRouter
        }
      ];
      vm.$router.addRoutes(
        rootRoute.concat([
          {
            path: "*",
            redirect: "/404"
          }
        ])
      );
    },
    signin: function(callback, data) {
      let vm = this;
      // 检查登录状态，如果未登录则跳转到登录页
      let localUser = util.session("token") || '';
      if (!localUser) {
        return vm.$router.push({
          path: "/login",
          query: { from: "root" }
        });
      }
      //设置请求头统一携带token
      // axios.defaults.headers.common["Authorization"] = "Bearer " + localUser.token;
      //获取用户信息及权限数据
      let userInfo = testdata.data;
      //取得资源权限对象
      let resourcePermission = vm.getPermission(userInfo);
      //使用资源权限设置请求拦截
      vm.setInterceptor(resourcePermission);
      //获得实际路由
      let allowedRouter = vm.getRoutes(userInfo);
      //若无可用路由限制访问
      // if (!allowedRouter || !allowedRouter.length) {
      //   util.session("token", "");
      //   return (document.body.innerHTML =
      //     "<h1>账号访问受限，请联系系统管理员！</h1>");
      // }
      //动态注入路由
      vm.extendRoutes(allowedRouter);
      //保存数据用作他处，非必需
      vm.menuData = util.buildMenu(userInfo.menus);
      vm.userData = userInfo;
      //权限检验方法
      Vue.prototype.$_has = function(rArray) {
        let resources = [];
        let permission = true;
        //提取权限数组
        if (Array.isArray(rArray)) {
          rArray.forEach(function(e) {
            resources = resources.concat(e.p);
          });
        } else {
          resources = resources.concat(rArray.p);
        }
        //校验权限
        resources.forEach(function(p) {
          if (!resourcePermission[p]) {
            return (permission = false);
          }
        });
        return permission;
      };
      //执行回调
      typeof callback === "function" && callback();
      // })
    },
    // 登录后定向
    loginDirect: function({ newPath, data }) {
      console.log(newPath, data);
      this.signin(() => {
        this.$router.replace({ path: newPath || "/overview" });
      }, data);
    },
    logoutDirect: function() {
      //清除session
      util.session("token", "");
      //清除请求权限控制
      axios.interceptors.request.eject(myInterceptor);
      //清除菜单权限
      this.$root.hashMenus = {};
      //清除请求头token
      axios.defaults.headers.common["Authorization"] = "";
      //回到登录页
      this.$router.replace({ path: "/login" });
    }
  },
  created: function(newPath) {
    this.signin();
  }
};
</script>

<style lang="less">
</style>
